package com.zhz.common.tool.email.autoconfig;

import com.zhz.common.tool.email.properties.JavaMailSenderProperties;
import com.zhz.common.tool.email.service.MailUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;

import java.util.Properties;

/**
 * 邮件自动装配
 *
 * @author zhouhengzhe
 * @version 1.0
 * @date 2023/4/23 17:11
 */
@Slf4j
@Configuration
@ConditionalOnProperty(prefix = "ihrm.mail", name = {"host", "username", "password", "port"}, matchIfMissing = false)
@EnableConfigurationProperties(JavaMailSenderProperties.class)
public class JavaMailSenderAutoConfiguration {
    @Bean
    public JavaMailSender javaMailSender(JavaMailSenderProperties javaMailSenderProperties) {

        JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();
        javaMailSender.setHost(javaMailSenderProperties.getHost());
        javaMailSender.setUsername(javaMailSenderProperties.getUsername());
        javaMailSender.setPassword(javaMailSenderProperties.getPassword());
        javaMailSender.setPort(javaMailSenderProperties.getPort());
        javaMailSender.setDefaultEncoding(javaMailSenderProperties.getDefaultEncoding().toString());
        Properties properties = new Properties();
        properties.putAll(javaMailSenderProperties.getProperties());
        javaMailSender.setJavaMailProperties(properties);
        return javaMailSender;
    }
    @Bean
    public MailUtils mailUtils(JavaMailSender javaMailSender) {
        return new MailUtils(javaMailSender);
    }

}
